import 'dart:async';
import 'dart:io';
import 'dart:math';

import 'package:bike_ride/common/mvvm/base_page.dart';
import 'package:bike_ride/common/util/account_manager.dart';
import 'package:bike_ride/common/util/extension.dart';
import 'package:bike_ride/common/util/format.dart';
import 'package:bike_ride/common/util/google_map_utils.dart';
import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/widget/avatar.dart';
import 'package:bike_ride/common/widget/circle_button_widget.dart';
import 'package:bike_ride/common/widget/dialog/mydialog.dart';
import 'package:bike_ride/common/widget/location_pin_widget.dart';
import 'package:bike_ride/common/widget/xb_button.dart';
import 'package:bike_ride/generated/l10n.dart';
import 'package:bike_ride/model/login/model/vehicle_geog_list_item_model.dart';
import 'package:bike_ride/model/main/model/park_m.dart';
import 'package:bike_ride/model/main/view_model/main_vm.dart';
import 'package:bike_ride/model/scan/view/scan_v.dart';
import 'package:bike_ride/res/style/color_styles.dart';
import 'package:bike_ride/res/style/text_styles.dart';
import 'package:bike_ride/router/navigator_util.dart';
import 'package:bike_ride/router/routers.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sliding_up_panel/sliding_up_panel.dart';

/// 这是App主体页面，主要是 PageView + BottomNavigationBar
class AppMainPage extends BaseStatefulPage {
  const AppMainPage({super.key});

  @override
  AppMainPageState createState() => AppMainPageState();
}

class AppMainPageState
    extends BaseStatefulPageState<AppMainPage, AppMainPageViewModel> {
  late PanelController controller;
  late double windowHeight;
  double _panelHeightOpen = 0;
  final double _panelHeightClosed = 500.rpx;
  final _tipsContainerHeight = 60.rpx;

  final isSelectStation = ValueNotifier(false);

  bool get canShowRechargeBtn {
    if(AccountManager.areaInfoM?.isOpenAreaRecharge != 1){
      return false;
    }
    if(AccountManager.areaInfoM?.isRechargeBalance == 1 && (AccountManager.areaInfoM?.rechargeRules != null && AccountManager.areaInfoM!.rechargeRules.isNotEmpty)){
      return true;
    }
    return false;
  }

  @override
  void initAttribute() {
    controller = PanelController();
    if (Platform.isAndroid) {
      SystemUiOverlayStyle style = const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent,
        statusBarIconBrightness: Brightness.dark,
      );
      SystemChrome.setSystemUIOverlayStyle(style);
    }
  }

  @override
  void initObserver() {}

  @override
  void initContextAttribute(BuildContext context) {
    super.initContextAttribute(context);

    viewModel!.devicePixelRatio = ImageConfiguration(
        devicePixelRatio:
            Platform.isAndroid ? MediaQuery.of(context).devicePixelRatio : 2);
  }

  @override
  AppMainPageViewModel viewBindingViewModel() {
    /// ViewModel 和 View 相互持有
    return AppMainPageViewModel()..viewState = this;
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    windowHeight = MediaQuery.of(context).size.height;
    _panelHeightOpen = windowHeight * .5;
  }

  void notifyChange() {
    if (mounted) {
      setState(() {});
    }
  }

  interceptNavigate(Function fn) async {
    if (AccountManager.isLogin) {
      fn();
    }else{
      NavigatorUtil.push(context, Routers.loginView);
    }
  }

  Future startLocation() async {
    GoogleMapUtils.getCurrentPosition((position)async{
      final kGooglePlex = CameraPosition(
        target: LatLng(position.latitude, position.longitude),
        zoom: max(viewModel!.mapZoom, 18),
      );

      final GoogleMapController controller =
          await viewModel!.mapController.future;
      await controller
          .animateCamera(CameraUpdate.newCameraPosition(kGooglePlex));
    });
  }

  ///[item] ParkM/VehicleGeogListItem
  void onVehicleOrStationMarkerTap(dynamic item) {
    GoogleMapUtils.getCurrentPosition((start){
      GoogleMapUtils.getDirections(LatLng(start.latitude, start.longitude),
          LatLng(item.lat!.toDouble(), item.lng!.toDouble()))
          .then((value) {
        final route = value!.routes!.first;
        viewModel!.infoWindowTitle =
        '${route.legs!.first.distance!.text} ${route.legs!.first.duration!.text} Go>';

        viewModel!.polyLines = {
          Polyline(
            polylineId: const PolylineId('polyline'),
            points: route.legs!.first.steps!
                .map((e) => LatLng(e.endLocation!.lat!.toDouble(),
                e.endLocation!.lng!.toDouble()))
                .toList(),
            color: ColorStyles.color_1E88E5,
            width: 4,
            jointType: JointType.round,
            startCap: Cap.roundCap,
          )
        };
        notifyChange();
      });
    });

    viewModel!.infoModel = item;
    if(item is ParkM){
      viewModel!.infoId = item.areaId;
    }else if(item is VehicleGeogListItem){
      viewModel!.infoId = item.vid;
    }
    viewModel!.isShowInfoWindow = true;
    notifyChange();
  }

  @override
  Widget appBuild(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          launchConfirmationDialog();
          return false;
        },
        child: SlidingUpPanel(
            controller: controller,
            maxHeight: _panelHeightOpen,
            minHeight: _panelHeightClosed +
                (viewModel!.isShowTips ? _tipsContainerHeight : 0),
            parallaxEnabled: false,
            parallaxOffset: .5,
            body: SizedBox(
              width: MediaQuery.of(context).size.width,
              height: MediaQuery.of(context).size.height,
              child: Stack(
                fit: StackFit.expand,
                children: [
                  GoogleMap(
                    initialCameraPosition: CameraPosition(
                      target: LatLng(AccountManager.userLatitude!.toDouble(),
                          AccountManager.userLongitude!.toDouble()),
                      zoom: viewModel!.mapZoom,
                    ),
                    myLocationEnabled: true,
                    trafficEnabled: true,
                    zoomControlsEnabled: false,
                    myLocationButtonEnabled: false,
                    markers: <Marker>{
                      ...(isSelectStation.value)
                          ? viewModel!.stationMarkers
                          : viewModel!.markers,
                    },
                    polygons: <Polygon>{
                      ...(isSelectStation.value)
                          ? viewModel!.stationPolygons
                          : [],
                      ...viewModel!.areaPolygons
                    },
                    polylines: viewModel!.polyLines,
                    onTap: (latLng){
                      viewModel!.hiddenInfoWindow();
                    },
                    onMapCreated: (GoogleMapController controller) {
                      viewModel!.mapController.complete(controller);
                      startLocation();
                    },
                    onCameraMove: (CameraPosition position) {
                      if (isSelectStation.value) {
                        viewModel!.getAllNearbyPark(
                            lat: position.target.latitude,
                            lng: position.target.longitude);
                      } else {
                        viewModel!.getNearbyBike(
                            lat: position.target.latitude,
                            lng: position.target.longitude);
                      }
                    },
                  ),
                  if (!AccountManager.isLogin)
                    const Center(
                      child: LocationPinWidget(showText: true),
                    ),

                  /// 头像
                  Positioned(
                      top: MediaQuery.of(context).padding.top + 32.rpx,
                      left: 32.rpx,
                      child: Avatar(
                        defaultPath: 'assets/images/default_face.png',
                        bottomText: AccountManager.isLogin
                            ? S.current.myName
                            : S.current.toLogin,
                        onTap: () {
                          if (AccountManager.isLogin) {
                            NavigatorUtil.push(context, Routers.mineView);
                          } else {
                            NavigatorUtil.push(context, Routers.loginView);
                          }
                        },
                      )),

                  /// 侧边按钮
                  Positioned(
                      bottom: MediaQuery.of(context).padding.bottom +
                          _panelHeightClosed +
                          100.rpx,
                      right: 32.rpx,
                      child: Column(
                        children: [
                          ValueListenableBuilder(
                              valueListenable: isSelectStation,
                              builder: (context, mSelectStation, _) {
                                return Container(
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius:
                                      BorderRadius.circular(50.rpx)),
                                  child: Column(
                                    children: [
                                      CircleButtonWidget(
                                        path: 'assets/images/P.png',
                                        bgColor: mSelectStation
                                            ? Theme.of(context)
                                            .colorScheme
                                            .primary
                                            : Colors.black12,
                                        onClick: () {
                                          isSelectStation.value = !mSelectStation;
                                          if (isSelectStation.value) {
                                            viewModel!.getAllNearbyPark(
                                                lat: viewModel!.lat,
                                                lng: viewModel!.lng);
                                          }
                                          viewModel!.hiddenInfoWindow();
                                        },
                                      ),
                                      SizedBox(
                                        height: 10.rpx,
                                      ),
                                      CircleButtonWidget(
                                        path: 'assets/images/ic_bike_nor.png',
                                        bgColor: mSelectStation
                                            ? Colors.black12
                                            : Theme.of(context)
                                            .colorScheme
                                            .primary,
                                        onClick: () {
                                          isSelectStation.value = !mSelectStation;
                                          if (!isSelectStation.value) {
                                            viewModel!.getNearbyBike(
                                                lat: viewModel!.lat,
                                                lng: viewModel!.lng);
                                          }
                                          viewModel!.hiddenInfoWindow();
                                        },
                                      ),
                                    ],
                                  ),
                                );
                              }),
                          SizedBox(
                            height: 28.rpx,
                          ),
                          CircleButtonWidget(
                            path: 'assets/images/location.png',
                            onClick: () {
                              startLocation();
                            },
                          ),
                          SizedBox(
                            height: 28.rpx,
                          ),
                          CircleButtonWidget(
                            path: 'assets/images/service.png',
                            onClick: () {
                              interceptNavigate(()=>NavigatorUtil.push(context, Routers.questionView));
                            },
                          )
                        ],
                      )),

                  /// 弹窗信息
                  if (viewModel!.isShowInfoWindow)
                    Positioned(
                      bottom: MediaQuery.of(context).padding.bottom + 28.rpx +
                          _panelHeightClosed +(viewModel!.isShowTips ? _tipsContainerHeight : 0),
                      left: 0,
                      right: 0,
                      child: _buildInfoDialog(),
                    ),
                ],
              ),
            ),
            panelBuilder: (sc) => _panel(sc),
            color: Colors.transparent,
            boxShadow: [
              BoxShadow(
                color: Colors.black.withAlpha(10),
                offset: Offset(4.rpx, 0),
                blurRadius: 24.rpx,
                spreadRadius: 8.rpx,
              )
            ],
        ),
    );
  }

  Widget _buildInfoDialog() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 22.rpx,vertical: 22.rpx),
      margin: EdgeInsets.symmetric(horizontal: 28.rpx),
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.rpx),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withAlpha(10),
              offset: Offset(4.rpx, 0),
              blurRadius: 24.rpx,
            )
          ]),
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (viewModel!.infoModel is VehicleGeogListItem) ...[
                Row(
                  children: [
                    Text(
                      '${S.current.vehicleNumber}:',
                      style: TextStyles.style_000000_12,
                    ),
                    Text(
                      '${(viewModel!.infoModel as VehicleGeogListItem).vid}',
                      style: TextStyles.style_page_title,
                    ),
                  ],
                )
              ],
              if (viewModel!.infoModel is ParkM) ...[
                ConstrainedBox(constraints: BoxConstraints(minHeight: 30.rpx),child: Text(
                  '${(viewModel!.infoModel as ParkM).groupName}',
                  style: TextStyle(
                    color: ColorStyles.color_0A1B29,
                    fontSize: 28.rpx,
                    fontWeight: FontWeight.w500,
                  ),
                ),),
                Text(
                  '${(viewModel!.infoModel as ParkM).addr}',
                  style: TextStyle(
                    color: ColorStyles.color_999999,
                    fontSize: 24.rpx,
                  ),
                ),
              ]
            ],
          ),
          Positioned(right: -32.rpx,top: -32.rpx,child: CloseButton(
            onPressed: () {
              viewModel!.isShowInfoWindow = false;
              viewModel!.infoModel = null;
              viewModel!.polyLines.clear();
              notifyChange();
            },
          ),)
        ],
      ),
    );
  }

  Widget _panel(ScrollController sc) {
    return SizedBox(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: Stack(
        children: [
          Observer(
              builder: (_) {
                if(viewModel!.unPayStore.unPayOrderList.isNotEmpty || viewModel!.unPayStore.violationList.isNotEmpty){
                  return Align(
                    alignment: Alignment.topCenter,
                    child: Container(
                      padding: EdgeInsets.only(
                          left: 24.rpx, right: 24.rpx, top: 10.rpx, bottom: 52.rpx),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(32.rpx),
                            topRight: Radius.circular(32.rpx)),
                        gradient: const LinearGradient(
                          colors: [
                            Color(0xFFA1D4FF),
                            Color(0xFFFFD1C7),
                            Color(0xFFFFE8B8),
                          ],
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            viewModel!.unPayStore.mainViewText,
                            style: TextStyle(
                                color: ColorStyles.color_333333,
                                fontSize: 28.rpx),
                          ),
                          GestureDetector(
                            onTap: () {
                              viewModel!.unPayStore.onEnter();
                            },
                            child: Container(
                              padding: EdgeInsets.only(
                                  left: 12.rpx,
                                  right: 12.rpx,
                                  top: 2.rpx,
                                  bottom: 4.rpx),
                              decoration: BoxDecoration(
                                color: Theme.of(context).colorScheme.primary,
                                borderRadius: BorderRadius.circular(20.rpx),
                              ),
                              child: Text(
                                S.current.check,
                                style: TextStyle(
                                    color: ColorStyles.color_FFFFFF,
                                    fontSize: 28.rpx),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  );
                }else{
                  return const SizedBox();
                }
              }),

          Positioned(
            top: (viewModel!.isShowTips ? _tipsContainerHeight : 0),
            left: 0,
            right: 0,
            bottom: 0,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                slidingDownPanelWidget(),
                Expanded(
                  child: Container(
                    margin: EdgeInsets.only(top: 8.rpx),
                    padding: const EdgeInsets.only(left: 10, right: 10),
                    decoration: const BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.only(
                            topRight: Radius.circular(12),
                            topLeft: Radius.circular(12))),
                    child: ListView(
                      controller: sc,
                      padding: EdgeInsets.symmetric(vertical: 16.rpx),
                      children: [
                        Row(
                          children: [
                            if (canShowRechargeBtn) ...[
                              XbButton(
                                width: 192.rpx,
                                isDefault: false,
                                borderRadius:
                                    const BorderRadius.all(Radius.circular(8)),
                                color: const Color(0xFFFF8D1A),
                                onPressed: () {
                                  interceptNavigate(()=>NavigatorUtil.push(
                                      context, Routers.walletView,
                                      arguments: {
                                        'show_charge_dialog': true,
                                      }).then((value) {
                                    viewModel?.getBrandAreaInfo();
                                  }));
                                },
                                child: Text(S.current.toRecharge),
                              ),
                              SizedBox(
                                width: 16.rpx,
                              )
                            ],
                            Expanded(
                              child: XbButton(
                                width: 192.rpx,
                                isDefault: false,
                                borderRadius:
                                    const BorderRadius.all(Radius.circular(8)),
                                onPressed: () {
                                  if (viewModel!
                                          .unPayStore.unPayOrderList.length >=
                                      (AccountManager
                                              .brandInfo?.currentOrderNum ??
                                          1)) {
                                    viewModel!.unPayStore.showTipDialog();
                                    return;
                                  }
                                  interceptNavigate(
                                    () => NavigatorUtil.push(
                                            context, Routers.qrcodeScanPage)
                                        .then((value) async{
                                      if (value != null && mounted) {
                                        final scanRul = value as String?;
                                        var brandCode = decodeVidBrandCode(scanRul);
                                        final result = await AccountManager.updateBrandCode(brandCode);
                                        if(result == true){
                                          var code = decodeEquipmentCode(scanRul);
                                          if(mounted && context.mounted) {
                                            goToUnLockPage(context, code);
                                          }
                                        }
                                      }
                                    }),
                                  );
                                },
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Image.asset(
                                      'assets/images/scan.png',
                                      width: 36.rpx,
                                      height: 36.rpx,
                                    ),
                                    const SizedBox(
                                      width: 4,
                                    ),
                                    Text(S.current.scanCodeToRide)
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        GridView(
                          shrinkWrap: true,
                          padding: EdgeInsets.only(top: 4.rpx),
                          gridDelegate:
                              SliverGridDelegateWithFixedCrossAxisCount(
                            mainAxisSpacing: 16.rpx,
                            crossAxisSpacing: 24.rpx,
                            crossAxisCount: 4,
                            childAspectRatio: 0.95,
                          ),
                          children: [
                            flexBottomSpreadItem(
                                key: S.current.enterCodeUnlockCar,
                                path: 'assets/common_v2/input_code_icon.png',
                                click: () {
                                  interceptNavigate(()=> NavigatorUtil.push(
                                      context, Routers.enterCodePage));
                                }),
                            flexBottomSpreadItem(
                                key: S.current.cycleFitCase,
                                path: 'assets/common_v2/buy_card_icon.png',
                                click: () {
                                  EasyLoading.showError(
                                      S.current.developerTips);
                                }),
                            flexBottomSpreadItem(
                                key: S.current.cycleRule,
                                path: 'assets/common_v2/cycling_icon.png',
                                click: () {
                                  interceptNavigate(()=>NavigatorUtil.push(
                                      context, Routers.webViewPage, arguments: {
                                    'url':
                                    '${AccountManager.baseUrl}/cycling_rule.html'
                                  }));
                                }),
                            flexBottomSpreadItem(
                                key: S.current.chargeStandard,
                                path: 'assets/common_v2/freightBasis.png',
                                click: () {
                                  interceptNavigate(()=>NavigatorUtil.push(
                                      context, Routers.freightView));
                                }),
                            flexBottomSpreadItem(
                                key: S.current.applyParkingArea,
                                path: 'assets/common_v2/map_apply_stop.png',
                                click: () {
                                  EasyLoading.showError(
                                      S.current.developerTips);
                                }),
                            flexBottomSpreadItem(
                                key: S.current.backLessCar,
                                path: 'assets/common_v2/map_bike_feedback.png',
                                click: () {
                                  EasyLoading.showError(
                                      S.current.developerTips);
                                }),
                            flexBottomSpreadItem(
                                key: S.current.safeStudy,
                                path: 'assets/common_v2/safe_class_v2.png',
                                click: () {
                                  interceptNavigate(()=>NavigatorUtil.push(
                                      context, Routers.webViewPage, arguments: {
                                    'url':
                                    '${AccountManager.baseUrl}/safe_class.html'
                                  }));
                                }),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  ///底部按钮操作
  Widget flexBottomSpreadItem(
      {required String key, required String path, required Function() click}) {
    return GestureDetector(
      onTap: click,
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 4),
            child: Image(
              width: 40,
              height: 40,
              image: AssetImage(path),
            ),
          ),
          Text(
            key.fixAutoLines(),
            style: TextStyle(
              color: ColorStyles.color_333333,
              fontSize: 24.rpx,
              fontWeight: FontWeight.w700,
            ),
            textAlign: TextAlign.center,
          )
        ],
      ),
    );
  }

  Widget slidingDownPanelWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 28,
          height: 4,
          decoration: BoxDecoration(
            color: Colors.black.withAlpha(20),
            borderRadius: BorderRadius.circular(4),
          ),
        )
      ],
    );
  }

  void launchConfirmationDialog() {
    // 显示确认对话框
    showAlertDialog(
      context: context,
      confirmName: S.current.confirm,
      cancelName: S.current.cancel,
      title: S.current.dialogTitle,
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset('assets/common_v2/icon_bus_routes_new.png',
            width: 96.rpx,
            height: 96.rpx,),
          SizedBox(height: 16.rpx,),
          Text(S.current.sureLeaveAPP,style: TextStyle(fontSize: 28.rpx,color: ColorStyles.color_333333),)
        ],
      ),
      onConfirm: () async{
        await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
      },
    );
  }
}
